package com.hsq.spzx.common.log.aspect;

import com.hsq.spzx.common.log.annotation.Log;
import com.hsq.spzx.common.log.service.AsyncOperLogService;
import com.hsq.spzx.common.log.utils.LogUtil;
import com.hsq.spzx.model.entity.system.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author hsq
 * @date 2025-06-12 下午5:29
 */

/**
 * // 环绕通知切面类定义
 */
@Component
@Slf4j
@Aspect
public class LogAspect {

    @Autowired
    private AsyncOperLogService asyncOperLogService ;

    //环绕通知
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog) {
//        String title = sysLog.title();
//        log.info("LogAspect...doAroundAdvice方法执行了"+title);
        // 构建前置参数
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(sysLog, joinPoint, sysOperLog);
        //业务方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            // 执行业务方法
            LogUtil.afterHandlLog(sysLog , proceed , sysOperLog , 0 , null) ;
            // 构建响应结果参数
//            log.error("在业务方法之后执行了...");
        } catch (Throwable e) {
            // 业务方法执行产生异常
            e.printStackTrace();    // 打印异常信息
            LogUtil.afterHandlLog(sysLog , proceed , sysOperLog , 1 , e.getMessage()) ;
            throw new RuntimeException();
        }
        // 保存日志数据
        asyncOperLogService.saveSysOperLog(sysOperLog);
        return proceed;
    }
}
